package yw.nmh.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author WangZhixian
 * @description
 * @date 2021/4/27
 */
public class ByteUtil {

    /**
     * 合并byte[]数组 （不改变原数组）
     * @param firstByte
     * @param secondByte
     * @return 合并后的数组
     */
    public static byte[] byteMerger(byte[] firstByte, byte[] secondByte){
        byte[] thirdByte = new byte[firstByte.length+secondByte.length];
        System.arraycopy(firstByte, 0, thirdByte, 0, firstByte.length);
        System.arraycopy(secondByte, 0, thirdByte, firstByte.length, secondByte.length);
        return thirdByte;
    }

    /**
     * 截取byte数组   不改变原数组
     * @param b 原数组
     * @param off 偏差值（索引）
     * @param length 长度
     * @return 截取后的数组
     */
    public static byte[] subByte(byte[] b,int off,int length){
        byte[] b1 = new byte[length];
        System.arraycopy(b, off, b1, 0, length);
        return b1;
    }

    /***
     * 将若干字节数组全部写入内存中，之后将其转化为字节数组
     *
     * @param sourceByteArray
     * @return byte[] 合并后的数组
     * @author wangzhixian
     * @date 2021/04/27
     */
    public static byte[] mergeByteByStream(byte[]... sourceByteArray) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        for (int i = 0; i < sourceByteArray.length; i++) {
            os.write(sourceByteArray[i]);
        }
        byte[] targetByteArray = os.toByteArray();
        os.close();
        return targetByteArray;
    }

    /**
     * 拆分原数组,截取两个byte数组一半   不改变原数组
     * @param source 原数组
     * @return 拆分截取后的数组
     */
    public static byte[][] subHalfByte(byte[] source){
        int halfOff = source.length/2;
        byte[] target1 = new byte[halfOff];
        byte[] target2 = new byte[source.length - halfOff];
        System.arraycopy(source, 0, target1, 0, target1.length);
        System.arraycopy(source, halfOff, target2, 0, target2.length);
        byte[][] bytes = new byte[2][];
        bytes[0] = target1;
        bytes[1] = target2;
        return bytes;
    }
}
